<template>
  <div class="common-dialog">
    <el-dialog
      title="添加分类"
      width="50%"
      :model-value="props.modelValue"
      @update:modelValue="closeDialog"
    >
      <el-form label-width="80px" class="dialog-form" :model="formData">
        <el-form-item label="序号">
          <el-input disabled v-model="formData.id" placeholder="系统生成"></el-input>
        </el-form-item>
        <el-form-item label="分类名称">
          <el-input
            v-model="formData.categoryName"
            placeholder="请输入分类名称"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="saveCategory">添加</el-button>
          <el-button @click="closeDialog">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script lang="js" setup>
import { ref, defineProps, defineEmits, watch } from "vue";
import { ElMessage } from "element-plus";
import instance from "@/utils/request";

const formData = ref({
  id: '',
  categoryName: '',

});
// 接收父组件传递的值
const props = defineProps({
  modelValue: Boolean, // v-model 默认属性名
  //接收表格数据
  newFormData: Object,
});
// 定义向父组件发送的事件
const emit = defineEmits(["update:modelValue", "update"]);
watch(() => props.newFormData, (newValue) => {
  if (newValue) {
    console.log('newValue', newValue)
    formData.value = JSON.parse(JSON.stringify(newValue)); // 更新表单数据
    console.log('formData', formData.value)
  }
}, { immediate: true });

const saveCategory = async() => {
  if (formData.value.id === undefined || formData.value.id === '') {
    // 添加分类
   const response = await instance.post('category/uploadCategory', {
      categoryName: formData.value.categoryName,
   });
   console.log(response.data);
   if (response.data.code === 200) {
     ElMessage.success("添加成功！");
     emit("update", response.data);
   } else {
     ElMessage.error("添加失败！");
   }

  } else if (formData.value.id !== undefined && formData.value.id !== '') {
    // 修改分类
    console.log("修改分类:");
    const response = await instance.put('category/updateCategory', {
      id: formData.value.id,
      categoryName: formData.value.categoryName,
    });
    if (response.data.code === 200) {
      ElMessage.success("修改成功！");
      emit("update", response.data);
    } else {
      ElMessage.error("修改失败！");
    }
  } else if (formData.value.categoryName === "") {
    ElMessage.error("分类名称不能为空！");
  }
};
// 关闭弹窗方法
const closeDialog = () => {
  emit("update:modelValue", false);
};
</script>
